from datetime import datetime
import json
from paho.mqtt import client as mqtt
from data.models import Data

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print('Connected to mqtt-server')
        client.subscribe('dsq/1419/107', qos=1)

def on_message(client, userdata, message):
    if message.topic == 'dsq/1419/107':
        res = json.loads((message.payload).decode('utf-8'))
        Data.objects.create(cardNum=res.get('cardNum'), deviceId=res.get('deviceId'), date=datetime.now()).save()
        print(message.topic, res)

def mqtt_run():
    mqtt_client.loop_start()

mqtt_client = mqtt.Client(
    client_id='dsq',
    clean_session=True
)
mqtt_client.connect(
    'broker.emqx.io',
    port=1883
)
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_run()